package com.base.api.cdr;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.api.pms.PmsPublicSqlQuery;
import com.base.utils.TreeUtil;
import com.cenboomh.mr.parser.DiseaseDocParser;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wnhuang
 * @Package com.base.api.cdr
 * @date 2020-12-23 21:45
 */
@Component
public class MedicalRecordInfoDetail extends PmsPublicSqlQuery {
    @Override
    public String splicSql(String sql, Map<String, Object> param) {
        StringBuilder param1 = new StringBuilder();
        if (param != null) {
            param1.append(" and docid = '" + param.get("key") + "'");
            return MessageFormat.format(sql.replace("'", "''"), param1.toString());
        } else {
            return "select 1 ";
        }
    }

    @Override
    public Map<String, Object> beforReturn(Map<String, Object> map) {
        ArrayList<Map<String, Object>> list =  (ArrayList<Map<String, Object>>)map.get("Data");
        Map<String, Object> data = list.get(0);
        byte[] bytes = (byte[]) data.get("DocXml");
        data.put("docText",parseXml(bytes));
        return map;
    }

    public String parseXml(byte[] bytes) {
        DiseaseDocParser parser = null;
        StringBuilder result = null;
        try {
            parser = new DiseaseDocParser(new String(bytes, "UTF-8"));
            // 获取整个文档的Map结构
            Map<String, Object> documentMap = parser.getDocumentMap();
            result = new StringBuilder("");
            for (Map.Entry<String, Object> entry : documentMap.entrySet()) {
                if (!"header".equals(entry.getKey()) && !"footer".equals(entry.getKey())) {
                    Map<String, String> map1 = (Map<String, String>) entry.getValue();
                    result.append("【" + map1.get("_displayName") + "】 ").append(map1.get("_text") == null ? map1.get("_value") : map1.get("_text") + "<br/>");
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

}
